package com.example.filelock.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.example.filelock.R;
import com.example.filelock.entity.JsonVersion;
import com.example.filelock.utils.BasDataUtil;
import com.example.filelock.utils.FileUtil;
import com.example.filelock.utils.MyHttp;
import com.example.filelock.utils.PageViewUitl;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

public class SetActivity extends AppCompatActivity {

    List<SetDataEntity> setDataEntities;
    private Toolbar mSetToolbar;
    private ListView mSetLvList;
    private SetLvViewAdapter setLvViewAdapter;
    private SwipeRefreshLayout mSetRefresh;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private AlertDialog alertDialog;
    public static int SET_RETURN = 10;
    private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set);
//        初始化导航栏
        PageViewUitl.initView(this);
        initView();
        setView();
    }

    private void setView() {

    }

    private void initView() {
        mSetToolbar = (Toolbar) findViewById(R.id.set_toolbar);
        mSetLvList = (ListView) findViewById(R.id.set_lv_list);
        mSetRefresh = (SwipeRefreshLayout) findViewById(R.id.set_refresh);
        mSetRefresh.setColorSchemeColors(getResources().getColor(R.color.mainColor));
        mSetRefresh.setEnabled(false);
        setDataEntities = new ArrayList<>();
        setLvViewAdapter = new SetLvViewAdapter();
        mSetLvList.setAdapter(setLvViewAdapter);
        sp = getSharedPreferences(BasDataUtil.SP_MAIN, MODE_PRIVATE);
        editor = sp.edit();
//        初始化初将
        initData();
    }

    //    初始化数据
    private void initData() {
        SetDataEntity setDataEntity;
        setDataEntity = new SetDataEntity();
        setDataEntity.isViewMsg = true;
        setDataEntity.itemMsg = "检查更新" + PageViewUitl.getVersionName(this);
        setDataEntity.topMsg = "更新";
        setDataEntity.contentMsg = "你的当前版本是：" + PageViewUitl.getVersionName(this) + "\n是否需要查询最新版本?";
        setDataEntities.add(setDataEntity);
        setDataEntity = new SetDataEntity();
        setDataEntity.isViewMsg = true;
        setDataEntity.itemMsg = "查询储存路径";
        setDataEntity.contentMsg = "加密文件路径:\n手机储存:T_FileLock/encryption\n解密文件路径:\n手机储存:T_FileLock/decryption";
        setDataEntity.topMsg = "清除";
        setDataEntities.add(setDataEntity);
        setDataEntity = new SetDataEntity();
        setDataEntity.isViewMsg = false;
        String isS = sp.getBoolean(BasDataUtil.SP_AutoFIle, true) ? "开启" : "关闭";
        setDataEntity.itemMsg = "自动清除临时文件:" + isS;
        setDataEntity.contentMsg = "建议用户开启此操作\n如果关闭,文件解密时会出现文件覆盖的问题!";
        setDataEntities.add(setDataEntity);
        setDataEntity = new SetDataEntity();
        setDataEntity.isViewMsg = false;
        setDataEntity.itemMsg = "手动清除临时文件";
        setDataEntity.contentMsg = "临时文件简述:\n加密时未成功的zip文件\n解密文件夹所有文件";
        setDataEntities.add(setDataEntity);
        setDataEntity = new SetDataEntity();
        setDataEntity.isViewMsg = false;
        setDataEntity.itemMsg = "清除所有文件";
        setDataEntity.contentMsg = "此操作只建议在卸载软件时操作!";
        setDataEntities.add(setDataEntity);
        setDataEntity = new SetDataEntity();
        setDataEntity.isViewMsg = true;
        setDataEntity.itemMsg = "关于与反馈";
        setDataEntity.contentMsg = "将会进入作者主页，选择联系模块即可提出反馈!";
        setDataEntity.topMsg = "关于";
        setDataEntities.add(setDataEntity);
        setDataEntity = new SetDataEntity();
        setDataEntity.isViewMsg = true;
        setDataEntity.itemMsg = "退出软件";
        setDataEntity.contentMsg = "是否退出软件!";
        setDataEntity.topMsg = "退出";
        setDataEntities.add(setDataEntity);
        setLvViewAdapter.notifyDataSetChanged();
    }

    //    list实体类
    private class SetDataEntity {
        public boolean isViewMsg;
        public String topMsg;
        public String itemMsg;
        public String contentMsg;
    }
//    操作对话框

    /**
     * 操作对话框
     *
     * @param content  //提示框内容
     * @param position //模块码
     */
    private void setDiaLog(String content, final int position) {
        alertDialog = new AlertDialog.Builder(this)
                .setTitle((position == 0 ? "更新" : position <= 4 ? "清除" : position==5?"关于":"退出") + "提示:")
                .setMessage(content)
                .setNegativeButton(position == 2 ? "关闭" : "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            if (position == 2) {
                                //关闭自动清理
                                if (!sp.getBoolean(BasDataUtil.SP_AutoFIle, true)) {
                                    Toast.makeText(getApplicationContext(), "当前处于开启状态", Toast.LENGTH_SHORT).show();
                                } else {
                                    editor.putBoolean(BasDataUtil.SP_AutoFIle, false);
                                    editor.commit();
                                    setDataEntities.get(position).itemMsg = sp.getBoolean(BasDataUtil.SP_AutoFIle, true) ? "自动清除临时文件:开启" : "自动清除临时文件:关闭";
                                    setDataEntities.set(position, setDataEntities.get(position));
                                    setLvViewAdapter.notifyDataSetChanged();
                                }
                            } else {
                                alertDialog.cancel();
                            }
                        } catch (Exception e) {
                            Log.d(BasDataUtil.LOG_TOAST, "设置页面开启自动错误:" + e.toString());
                        }
                    }
                })
                .setPositiveButton(position == 2 ? "开启" : position == 3 ? "清理" : "确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        try {
                            switch (position) {
                                case 0:
                                    mSetRefresh.setRefreshing(true);
                                    //检查更新
                                    MyHttp.post("http://tmm-tommy.cn:8888/tommy/user/getUserApk", getApplicationContext(), new Response.Listener<JSONObject>() {
                                        @Override
                                        public void onResponse(JSONObject jsonObject) {
                                            try {
                                                Gson gson = new Gson();
                                                JsonVersion jsonVersion = gson.fromJson(jsonObject.toString(), JsonVersion.class);
                                                if (jsonVersion.getCode() == 200) {
                                                    for (int i = 0; i < jsonVersion.getData().size(); i++) {
                                                        if (jsonVersion.getData().get(i).contains(getResources().getString(R.string.app_name_en)) ||
                                                                jsonVersion.getData().get(i).contains(getResources().getString(R.string.app_name_zh))) {
                                                            String version = jsonVersion.getData().get(i).split("\\$=\\$")[1];
                                                            if (version.equals(PageViewUitl.getVersionName(getApplicationContext()))) {
                                                                Toast.makeText(getApplicationContext(), "已经为最新版本", Toast.LENGTH_SHORT).show();
                                                            } else {
                                                                //下载软件
                                                                intent = new Intent();
                                                                intent.setAction("android.intent.action.VIEW");
                                                                Uri content_url = Uri.parse("http://tmm-tommy.cn:8888/tommy/apk/" + jsonVersion.getData().get(i) + ".apk");
                                                                intent.setData(content_url);
                                                                startActivity(intent);
                                                            }
                                                            break;
                                                        } else if (i == jsonVersion.getData().size() - 1) {
                                                            Toast.makeText(getApplicationContext(), "已经为最新版本!", Toast.LENGTH_SHORT).show();
                                                        }

                                                    }
                                                } else {
                                                    Toast.makeText(getApplicationContext(), "获取失败!", Toast.LENGTH_SHORT).show();
                                                }
                                                mSetRefresh.setRefreshing(false);
                                            } catch (Exception e) {
                                                mSetRefresh.setRefreshing(false);
                                                Toast.makeText(getApplicationContext(), "已经为最新版本!", Toast.LENGTH_SHORT).show();
                                                Log.d(BasDataUtil.LOG_TOAST, "检查更新错误:" + e
                                                        .toString());
                                            }

                                        }
                                    });
                                    break;
                                case 1:
                                    //查询路径
                                    break;
                                case 2:
                                    //开启自动清理
                                    if (sp.getBoolean(BasDataUtil.SP_AutoFIle, true)) {
                                        Toast.makeText(getApplicationContext(), "当前处于开启状态", Toast.LENGTH_SHORT).show();
                                    } else {
                                        editor.putBoolean(BasDataUtil.SP_AutoFIle, true);
                                        editor.commit();
                                        setDataEntities.get(position).itemMsg = sp.getBoolean(BasDataUtil.SP_AutoFIle, true) ? "自动清除临时文件:开启" : "自动清除临时文件:关闭";
                                        setDataEntities.set(position, setDataEntities.get(position));
                                        setLvViewAdapter.notifyDataSetChanged();
                                    }

                                    break;
                                case 3:
//                                手动清理临时文件
                                    mSetRefresh.setRefreshing(true);
                                    //消除临时文件
                                    FileUtil.deleteTemFile();
                                    mSetRefresh.setRefreshing(false);
                                    Toast.makeText(getApplicationContext(), "清除成功!", Toast.LENGTH_SHORT).show();
                                    break;
                                case 4:
//                                清除所有文件
                                    mSetRefresh.setRefreshing(true);
                                    //消除临时文件
                                    File file = new File(BasDataUtil.getMainPath());
                                    if (file.exists() && FileUtil.deleteDirectory(BasDataUtil.getMainPath())) {
                                        Toast.makeText(getApplicationContext(), "删除成功", Toast.LENGTH_SHORT).show();
                                    } else {
                                        Toast.makeText(SetActivity.this, "文件已经不存在!", Toast.LENGTH_SHORT).show();
                                    }
                                    mSetRefresh.setRefreshing(false);
                                    break;
                                case 5:
                                    //关于反馈
                                    intent = new Intent();
                                    intent.setAction("android.intent.action.VIEW");
                                    Uri content_url = Uri.parse("http://106.13.185.176:8889/" );
                                    intent.setData(content_url);
                                    startActivity(intent);
                                    break;
                                case 6:
                                    //退出软件
                                    intent = new Intent();
                                    intent.putExtra("back", "Back Data");
                                    setResult(SET_RETURN, intent);
                                    finish();
                                    break;
                            }
                        } catch (Exception e) {
                            Log.d(BasDataUtil.LOG_TOAST, "设置点击确定错误:" + e.toString());
                        }

                    }
                })
                .show();
    }

//    适配器

    public class SetLvViewAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return setDataEntities.size();
        }

        @Override
        public SetDataEntity getItem(int position) {
            return setDataEntities.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.set_lv_view, null);
                convertView.setTag(new ViewHolder(convertView));
            }
            initializeViews((SetDataEntity) getItem(position), (ViewHolder) convertView.getTag(), position);
            return convertView;
        }

        private void initializeViews(final SetDataEntity object, ViewHolder holder, final int position) {
            //TODO implement
            try {
                holder.setViewTvItemMsg.setText(object.itemMsg);
                if (object.topMsg != null)
                    holder.setViewTvTopMsg.setText(object.topMsg);
                if (object.isViewMsg) {
                    holder.setViewLayoutViews.setVisibility(View.VISIBLE);
                } else {
                    holder.setViewLayoutViews.setVisibility(View.GONE);
                }
//            点击item
                holder.setViewLayoutItem.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        setDiaLog(object.contentMsg, position);
                    }
                });
            }catch (Exception e){
                Log.d(BasDataUtil.LOG_TOAST,"设置适配器错误:"+e.toString());
            }

        }

        protected class ViewHolder {
            private LinearLayout setViewLayoutViews;
            private TextView setViewTvTopMsg;
            private RelativeLayout setViewLayoutItem;
            private TextView setViewTvItemMsg;

            public ViewHolder(View view) {
                setViewLayoutViews = (LinearLayout) view.findViewById(R.id.setView_layout_views);
                setViewTvTopMsg = (TextView) view.findViewById(R.id.setView_tv_topMsg);
                setViewLayoutItem = (RelativeLayout) view.findViewById(R.id.setView_layout_item);
                setViewTvItemMsg = (TextView) view.findViewById(R.id.setView_tv_itemMsg);
            }
        }
    }
}
